/*
* @(#)StepInformationWindow.java
*
* Copyright (c) 2004 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/

package com.dcivision.workflow.applet.editor;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.ObjectInputStream;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import org.jgraph.graph.DefaultEdge;
import org.jgraph.pad.GPUserObject;

import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.workflow.applet.AppletConstant;
import com.dcivision.workflow.applet.ListObject;
import com.dcivision.workflow.applet.WindowUtilities;
import com.dcivision.workflow.applet.net.HttpOperation;
import com.dcivision.workflow.bean.WorkflowStepFormEquat;

/**
    StepInformationWindow.java

    @author          Zealot
    @company         DCIVision Limited
    @creation date   27/08/2004
    @version         $Revision: 1.7 $
    */

public class FormDriveConnectionWindow extends JDialog {
  HttpOperation httpOperation=null;
  String hostURL = "";
  String workflowRecordID = null;
  String maintWorkflowRecordURL = "/workflow/MaintWorkflowRecord.do?fromType=A";
  String formEquation="";
  String formEquationItem="";
  boolean haveCompare=false;
  String operand1="";
  String operandDB1="";
  String operand2="";
  String operandDB2="";
  String compare="";
  String formEquationValue;
  int operand2StartIndex=0;
  int  expressionType=0;
  JPanel panel1 = new JPanel();
  JLabel jLabel1 = new JLabel();
  JTextField jTFRouteName = new JTextField();
  JButton jButton1 = new JButton();
  DefaultEdge edge = null;
  Editor editor = null;
  JCheckBox jCBDefault = new JCheckBox();
  JLabel jLabel2 = new JLabel();
  JLabel jLabel3 = new JLabel();
  JRadioButton jRBNum = new JRadioButton();
  ButtonGroup buttonGroup1 = new ButtonGroup();
  JRadioButton jRBStr = new JRadioButton();
  JRadioButton jRBDate = new JRadioButton();
  JTextField jTFDateFormat = new JTextField();
  ButtonGroup buttonGroup2 = new ButtonGroup();
  JRadioButton jRBElement = new JRadioButton();
  JRadioButton jRBOperand = new JRadioButton();
  JRadioButton jRBOperator = new JRadioButton();
  JComboBox jCBElement = new JComboBox();
  JComboBox jCBOperand = new JComboBox();
  JLabel jLabel4 = new JLabel();
  JTextField jTFFormEquation = new JTextField();
  JTextField jTFOperator = new JTextField();
  ItemListener itemTypeListener = null;
  JButton jButton2 = new JButton();
  JButton jButton3 = new JButton();
  JLabel jLabel5 = new JLabel();
  JComboBox jCBFormRecord = new JComboBox();

  public FormDriveConnectionWindow(Frame frame, String title, boolean modal) {
    super(frame, title, modal);
    try {
      jbInit();
      pack();
    }
    catch(Exception ex) {
      ex.printStackTrace();
    }
  }

  public FormDriveConnectionWindow() {
    this(null, "", false);
  }
  private void jbInit() throws Exception {
    panel1.setLayout(null);
    jLabel1.setForeground(Color.red);
    jLabel1.setText("Route Name:");
    jLabel1.setBounds(new Rectangle(30, 15, 92, 22));
    jTFRouteName.setText("");
    jTFRouteName.setBounds(new Rectangle(135, 15, 120, 22));
    jButton1.setBounds(new Rectangle(171, 289, 126, 25));
    jButton1.setText("OK");
    jButton1.addActionListener(new FormDriveConnectionWindow_jButton1_actionAdapter(this));
    jCBDefault.setText("jCheckBox1");
    jCBDefault.setBounds(new Rectangle(273, 15, 20, 17));
    jLabel2.setText("Defalut Route");
    jLabel2.setBounds(new Rectangle(310, 15, 105, 21));
    jLabel3.setText("Please select the operation type for this form equation: ");
    jLabel3.setBounds(new Rectangle(28, 71, 349, 21));
    jRBNum.setText("Number Operation");
    jRBNum.setBounds(new Rectangle(28, 94, 157, 22));
    jRBStr.setText("String Operation");
    jRBStr.setBounds(new Rectangle(28, 112, 155, 20));
    jRBDate.setText("Date Operation    Date Format: ");
    jRBDate.setBounds(new Rectangle(28, 129, 225, 20));
    jTFDateFormat.setText("dd-MM-yyyy HH:mm:ss");
    jTFDateFormat.setBounds(new Rectangle(253, 128, 149, 20));
    jRBElement.setSelected(true);
    jRBElement.setText("Select Form Element");
    jRBElement.setBounds(new Rectangle(28, 155, 151, 25));
    jRBOperand.setText("Select Operand");
    jRBOperand.setBounds(new Rectangle(189, 157, 121, 25));
    jRBOperator.setText("Set Operator");
    jRBOperator.setBounds(new Rectangle(309, 158, 129, 25));
    jCBElement.setBounds(new Rectangle(28, 186, 133, 21));
    jCBOperand.setBounds(new Rectangle(194, 187, 106, 22));
    jTFOperator.setText("");
    jTFOperator.setBounds(new Rectangle(319, 175, 151, 23));
    jLabel4.setForeground(Color.red);
    jLabel4.setText("Form Equation:");
    jLabel4.setBounds(new Rectangle(25, 249, 94, 21));
    jTFFormEquation.setText("");
    jTFFormEquation.setBounds(new Rectangle(123, 246, 344, 22));
    jTFOperator.setText("");
    jTFOperator.setBounds(new Rectangle(315, 185, 152, 22));
    jButton2.setBounds(new Rectangle(166, 216, 77, 25));
    jButton2.setText("Add");
    jButton2.addActionListener(new FormDriveConnectionWindow_jButton2_actionAdapter(this));
    jButton3.setBounds(new Rectangle(277, 216, 73, 25));
    jButton3.setText("Clear");
    jButton3.addActionListener(new FormDriveConnectionWindow_jButton3_actionAdapter(this));
    jLabel5.setText("Bind With:");
    jLabel5.setBounds(new Rectangle(31, 47, 72, 20));
    jCBFormRecord.setBounds(new Rectangle(135, 46, 230, 22));
    jCBFormRecord.addItemListener(new ItemListener(){
      public void itemStateChanged(ItemEvent event){
        int state = event.getStateChange();
        ListObject formRecord = (ListObject)event.getItem();
        String formRecordID = formRecord.getID();
        String getDataURL  = "/workflow/appletMiddleware?dataType=GET_FORMELEMENT"+"&workflowRecordID="+workflowRecordID+"&formRecordID="+formRecordID;
        Object obj = WindowUtilities.getObjectFromServlet(httpOperation,getDataURL);
        List formElementList = (List)(obj);
        jCBElement.removeAllItems();
        for(int i=0;i<formElementList.size();i++){
          FormElement formElement = (FormElement)formElementList.get(i);
          ListObject listObject = new ListObject();
          listObject.setID(WorkflowStepFormEquat.ELEMENT_PREFIX_CHAR+formElement.getID());
          listObject.setName(formElement.getFieldName());
          jCBElement.addItem(listObject);
        }
        
      }
    });
    this.getContentPane().add(panel1, BorderLayout.CENTER);
    buttonGroup1.add(jRBNum);
    buttonGroup2.add(jRBElement);
    buttonGroup2.add(jRBOperand);
    buttonGroup2.add(jRBOperator);
    panel1.add(jRBDate, null);
    panel1.add(jLabel3, null);
    panel1.add(jRBNum, null);
    panel1.add(jRBStr, null);
    panel1.add(jRBOperator, null);
    panel1.add(jRBElement, null);
    panel1.add(jRBOperand, null);
    panel1.add(jCBElement, null);
    panel1.add(jCBOperand, null);
    panel1.add(jTFOperator, null);
    panel1.add(jTFDateFormat, null);
    panel1.add(jLabel4, null);
    panel1.add(jTFFormEquation, null);
    panel1.add(jButton1, null);
    panel1.add(jButton3, null);
    panel1.add(jButton2, null);
    panel1.add(jTFRouteName, null);
    panel1.add(jLabel1, null);
    panel1.add(jCBDefault, null);
    panel1.add(jLabel2, null);
    panel1.add(jLabel5, null);
    panel1.add(jCBFormRecord, null);
    panel1.add(jTFOperator, null);
    buttonGroup1.add(jRBDate);
    buttonGroup1.add(jRBStr);
    itemTypeListener = new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        JRadioButton rb = (JRadioButton) e.getSource();
        if(rb==jRBNum&&rb.isSelected()){
          initOperand(1);
        } else if(rb==jRBStr&&rb.isSelected()){
          initOperand(2);
        } else if(rb==jRBDate&&rb.isSelected()){
          initOperand(3);
        }
      }
    };
    jRBNum.addItemListener(itemTypeListener);
    jRBStr.addItemListener(itemTypeListener);
    jRBDate.addItemListener(itemTypeListener);
    jRBNum.setSelected(true);
  }

  void initOperand(int index){
    jCBOperand.removeAllItems();
    if(index==1){
      addItems(AppletConstant.numOperand);
    }else if(index==2){
      addItems(AppletConstant.StrOperand);
    }else if(index==3){
      addItems(AppletConstant.dataOperand);
    }
  }
  void addItems(String[][] operand){
    for(int i=0;i<operand.length;i++){
      ListObject listObject = new ListObject();
      listObject.setName(operand[i][0]);
      listObject.setID(operand[i][1]);
      jCBOperand.addItem(listObject);
    }
  }

  public void initData(String workflowRecordID, HttpOperation httpOperation, String hostURL, Editor editor){
    this.workflowRecordID = workflowRecordID;
    this.httpOperation = httpOperation;
    this.hostURL = hostURL;
    this.editor = editor;
    String getDataURL  = "/workflow/appletMiddleware?dataType=GET_FORM"+"&workflowRecordID="+workflowRecordID;
    ObjectInputStream inputFromServlet = null;
    List formElementList = null;
    List formRecordList = null;
    try{
      inputFromServlet = httpOperation.getObjectInputStreamFromServlet(getDataURL);
      if(inputFromServlet == null){
        return;
      }
      Object obj = null;
      obj = inputFromServlet.readObject();
      if (obj instanceof List) {
        formElementList = (List) obj;
      } else if (obj instanceof Exception) {
        //otherwise type cast it to Exception and throw that exception.
      throw (Exception) obj;
      }
      obj = inputFromServlet.readObject();
      if (obj instanceof List) {
        formRecordList = (List) obj;
      } else if (obj instanceof Exception) {
        //otherwise type cast it to Exception and throw that exception.
      throw (Exception) obj;
      }
      for(int i=0;i<formElementList.size();i++){
        FormElement formElement = (FormElement)formElementList.get(i);
        ListObject listObject = new ListObject();
        listObject.setID(WorkflowStepFormEquat.ELEMENT_PREFIX_CHAR+formElement.getID());
        listObject.setName(formElement.getFieldName());
        jCBElement.addItem(listObject);
      }
      for(int i=0;i<formRecordList.size();i++){
        FormRecord formRecord = (FormRecord)formRecordList.get(i);
        ListObject listObject = new ListObject();
        listObject.setID(formRecord.getID().toString());
        listObject.setName(formRecord.getFormCode() + "(" + formRecord.getFormVersion() + ")");
        jCBFormRecord.addItem(listObject);
      }
    }catch(Exception e){
      e.printStackTrace();
    }
  }
  boolean checkValue(){

    return true;
  }

  void jButton1_actionPerformed(ActionEvent e) {
    //checkValue();
    if(!jCBDefault.isSelected()){   
      if(haveCompare==false||expressionType==0){
        editor.outputMessage("The form equation is illegal!",false);
        return;
      }
    }
    if(postDataToEdge()){
    }
    this.dispose() ;

  }

  public DefaultEdge getEdge(){
    return this.edge;
  }

  public void setEdge(DefaultEdge edge){
    this.edge = edge;
  }

  public Editor getEditor(){
    return this.editor;
  }

  public void setEditor(Editor editor){
    this.editor = editor;
  }

  void jButton2_actionPerformed(ActionEvent e) {
    formEquation = jTFFormEquation.getText();
    String formRecordName="";
    if(jCBFormRecord.getItemCount()>1){
      formRecordName=((ListObject)jCBFormRecord.getSelectedItem()).getName()+".";
    }
    if(jRBElement.isSelected()){
      if(expressionType==1){
        editor.outputMessage("Please add a operand first!",false);
        return;
      }
      expressionType=1;
      String elementName = ((ListObject)jCBElement.getSelectedItem()).getName();
      formEquation += " "+formRecordName+"["+elementName+"]";
      if(haveCompare){
        operand2+= ((ListObject)jCBElement.getSelectedItem()).getID()+"|";
      } else {
        operand1+= ((ListObject)jCBElement.getSelectedItem()).getID()+"|";
      }
    } else if(jRBOperand.isSelected()){
      if(expressionType==0){
        editor.outputMessage("Please add a form element or operator first!",false);
        return;
      }
      compare=((ListObject)jCBOperand.getSelectedItem()).getID();
      if(AppletConstant.numOperand[4][1].equals(compare)
          ||AppletConstant.numOperand[5][1].equals(compare)
			||AppletConstant.numOperand[6][1].equals(compare)
			||AppletConstant.numOperand[7][1].equals(compare)
			||AppletConstant.numOperand[8][1].equals(compare)
			||AppletConstant.StrOperand[1][1].equals(compare)
			||AppletConstant.StrOperand[2][1].equals(compare)
			||AppletConstant.StrOperand[3][1].equals(compare)
			||AppletConstant.dataOperand[0][1].equals(compare)
			||AppletConstant.dataOperand[1][1].equals(compare)
			||AppletConstant.dataOperand[2][1].equals(compare)){
        if(haveCompare){
          editor.outputMessage("There is a compared operand already!",false);
          return;
        } else {
          haveCompare = true;
        }
      }
      expressionType=0;
      String operandName = ((ListObject)jCBOperand.getSelectedItem()).getName();
      formEquation += " "+operandName;
      operand2StartIndex = formEquation.length();

    } else if(jRBOperator.isSelected()){
      if(expressionType==1){
        editor.outputMessage("Please add a operand first!",false);
        return;
      }
      String operatorName = jTFOperator.getText();
      if(jRBNum.isSelected()){
        if(!WindowUtilities.isNumber(operatorName)){
          editor.outputMessage("Operator must be a numeric!", false);
          return;
        }
      }else if(jRBDate.isSelected()){
        if(!WindowUtilities.isDate(operatorName)){
          editor.outputMessage("Operator is a illogic date!", false);
          return;
        }
      }
      expressionType=1;
      formEquation += " "+"'"+operatorName+"'";
      if(haveCompare){
        operand2+= operatorName+"|";
      } else {
        operand1+= operatorName+"|";
      }
    }
    jTFFormEquation.setText(formEquation);
  }

  void jButton3_actionPerformed(ActionEvent e) {

  }
  boolean postDataToEdge(){
    boolean isSuccess = true;
    if(jCBDefault.isSelected()){
      jTFRouteName.setText("Default Route");      
    }
    operand1=WindowUtilities.replaceString(operand1,"+","!!!");
    operand2=WindowUtilities.replaceString(operand2,"+","!!!");
    formEquation=WindowUtilities.replaceString(formEquation,"+","!!!");
    formEquationValue=jTFRouteName.getText()+WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    if(jCBDefault.isSelected()){
      formEquationValue+="Y";      
    } else {
      formEquationValue+="N";
    }
    formEquationValue+=WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    formEquationValue+=operand1;
    formEquationValue+=WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    formEquationValue+=operand2;
    formEquationValue+=WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    formEquationValue+=compare;
    formEquationValue+=WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    formEquationValue+=formEquation;
    formEquationValue+=WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    if(jRBNum.isSelected()){
      formEquationValue+=WorkflowStepFormEquat.OPERATION_TYPE_NUMBER;
    }else if(jRBStr.isSelected()){
      formEquationValue+=WorkflowStepFormEquat.OPERATION_TYPE_STRING;
    }else{
      formEquationValue+=WorkflowStepFormEquat.OPERATION_TYPE_DATE;
    }
    formEquationValue+=WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    formEquationValue+=jTFDateFormat.getText();
    formEquationValue+=WorkflowStepFormEquat.SPLIT_PREFIX_CHAR;
    GPUserObject userObject =new GPUserObject();
    userObject.setValue(jTFRouteName.getText());
    //userObject.putProperty("EQUATION", formEquationValue);
    userObject.putProperty("TYPE","D"+AppletConstant.SPLITCHAR+jTFRouteName.getText()+"#"+formEquationValue);
    //userObject.putProperty("TYPE", WorkflowStep.PARENT_TYPE_FROM_VALUE_DRIVEN);
    edge.setUserObject(userObject);
    //editor.outputMessage(((GPUserObject)edge.getUserObject()).getProperty("formEquationValue").toString(),false);
    /*try{
      httpOperation.reset() ;
      httpOperation.setSubmissionURL(hostURL+maintWorkflowRecordURL);
      httpOperation.addHtmlFormText(new HtmlFormText("opMode", "INS" ));
      httpOperation.addHtmlFormText(new HtmlFormText("formEquationValue", formEquationValue ));
      String returnValue = httpOperation.transmit().toString();
      returnValue = returnValue.replaceAll("\n","");
      editor.outputMessage(returnValue, false);
      isSuccess = true;
    }catch(Exception e){
      e.printStackTrace();
      isSuccess = false;
    }*/
    return isSuccess;
  }
}

class FormDriveConnectionWindow_jButton1_actionAdapter implements java.awt.event.ActionListener {
  FormDriveConnectionWindow adaptee;

  FormDriveConnectionWindow_jButton1_actionAdapter(FormDriveConnectionWindow adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.jButton1_actionPerformed(e);
  }
}

class FormDriveConnectionWindow_jButton2_actionAdapter implements java.awt.event.ActionListener {
  FormDriveConnectionWindow adaptee;

  FormDriveConnectionWindow_jButton2_actionAdapter(FormDriveConnectionWindow adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.jButton2_actionPerformed(e);
  }
}

class FormDriveConnectionWindow_jButton3_actionAdapter implements java.awt.event.ActionListener {
  FormDriveConnectionWindow adaptee;

  FormDriveConnectionWindow_jButton3_actionAdapter(FormDriveConnectionWindow adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.jButton3_actionPerformed(e);
  }
}
